<?php
namespace api\components;

use Yii; 
use yiike\user\models\Token;

/**
 * Site controller
 */
class UserController extends Controller
{
    /**
     * @var \yiike\user
     */
    private $_user = false;
    
    public function beforeAction($action)
    {
        if ($this->checkToken()) {
            return parent::beforeAction($action);
        }
        else {
            parent::afterAction($action, ['code' => 100030]);
        }
    }
    
    private function checkToken() {
        $token = Yii::$app->request->post('token') ? : Yii::$app->request->get('token');
        
        $tokenModel = Token::findOne(['code' => $token, 'type' => Token::TYPE_LOGIN]);
        if ($tokenModel && ($user = $tokenModel->user)) {
            $this->_user = $user;
            return Yii::$app->getUser()->login($user);
        } else {
            return false;
        }
    }
    
    public function getUser() {
        return $this->_user;
    }
}
